package com.cjh.filter;

import com.cjh.constant.JwtConstant;
import com.cjh.entity.LoginUser;
import com.cjh.exception.ResultException;
import com.cjh.utils.JwtUtils;
import com.cjh.utils.RedisUtil;
import com.cjh.utils.ResponseUtil;
import com.cjh.utils.ResultJson;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * jwt过滤器
 */
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private RedisUtil redisUtil;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

        //获取token
        String token = request.getHeader(JwtConstant.AUTHORIZATION);
        if (Objects.isNull(token)){
            //放行请求
            filterChain.doFilter(request,response);
            return;
        }
        //解析token
        String userId = JwtUtils.parseToken(response,token);

        //token解析通过
        if (!Objects.isNull(userId)){
            //从redis获取用户信息
            LoginUser loginUser = (LoginUser) redisUtil.get(JwtConstant.JWT_PREFIX + userId);
            if (Objects.isNull(loginUser)){
                ResponseUtil.returnJson(response,ResultJson.fail(401,"认证失效,请重新登录"));
                return;
            }

            //获取权限信息封装到Authentication
            UsernamePasswordAuthenticationToken authenticationToken=new UsernamePasswordAuthenticationToken(loginUser,null,loginUser.getAuthorities());
            //将用户信息存入SecurityContextHolder
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
            //放行请求
            filterChain.doFilter(request,response);
        }

    }
}
